#include <stdio.h>
#include "log_writer.h"
#include "time_recorder.h"

using namespace std;
namespace andrew
{
	namespace tools
	{
		namespace log
		{
			log_writer::log_writer()
			{

			}

			log_writer::~log_writer()
			{
				if(file_writer.is_open())
				{
					file_writer<<"========log file end========"<<endl;
					file_writer.close();
				}
				pthread_mutex_destroy(&log_mtx);
			}	
			int log_writer::init(unsigned int _tmp_max_line,const char* _tmp_log_path)
			{
				log_max_line = (_tmp_max_line == 0)? DEFAULT_LOG_MAX_LINE:_tmp_max_line;
				memset(sz_log_path,0,sizeof(sz_log_path));
				strcpy(sz_log_path,_tmp_log_path);
				snprintf(sz_file_name,MAX_FILE_PATH,"%s/log_0.log",sz_log_path);
				file_writer.open(sz_file_name,ios_base::out);
				if(!file_writer.is_open())
				{
					return ERROR;
				}
				file_writer<<"========log file begin========"<<endl;
				succ_case_count ++;

				return OK;
			}
			int log_writer::write(const char* _tmp_log)
			{
				pthread_mutex_lock(&log_mtx);
				if(file_writer.is_open())
				{
					if(succ_case_count % log_max_line) 
					{
						if(file_writer<<logtime()<<LOG_SEP
								<<_tmp_log<<endl)
							succ_case_count ++;
						else
							err_case_count ++;
					}
					else
					{
						//new file
						file_writer<<"========log file end========"<<endl;
						file_writer.close();
						snprintf(sz_file_name,MAX_FILE_PATH,"%s/log_%d.log",sz_log_path,
								succ_case_count / log_max_line);
						file_writer.open(sz_file_name,ios_base::out);
						if(file_writer.is_open())
						{
							file_writer<<"========log file begin========"<<endl;

							succ_case_count ++;
						}
						else
							return ERROR;


					}
				}
				pthread_mutex_unlock(&log_mtx);
				return OK;
			}
			int log_writer::record_time_end(const char* _tmp_log)
			{
				pthread_mutex_lock(&log_mtx);
				if(file_writer.is_open())
				{
					file_writer<<logtime()<<LOG_SEP
						<<_tmp_log<<LOG_SEP
						<<andrew::tools::common::time_recorder::record_end()<<LOG_SEP
						<<LOG_TIME_UNIT<<endl;
					succ_case_count ++;

				}
				else
					return ERROR;
				pthread_mutex_unlock(&log_mtx);
				return OK;
			}
			int log_writer::record_time_begin(const char* _tmp_log)
			{
				pthread_mutex_lock(&log_mtx);
				andrew::tools::common::time_recorder::record_begin();
				if(file_writer.is_open())
				{
					file_writer<<logtime()<<LOG_SEP
						<<_tmp_log<<endl;
					succ_case_count ++;
				}
				else
					return ERROR;
				pthread_mutex_unlock(&log_mtx);
				return OK;
			}
			char* log_writer::logtime()
			{
				static char sTime[32] = {0};
				time(&iCurrTime);
				localtime_r(&iCurrTime, &stCurrTime);
				gettimeofday(&ms,NULL);
				sprintf(sTime, "%04d-%02d-%02d %02d:%02d:%02d",
						stCurrTime.tm_year + 1900,
						stCurrTime.tm_mon+1, stCurrTime.tm_mday,
						stCurrTime.tm_hour, stCurrTime.tm_min, 
						stCurrTime.tm_sec);
				return sTime;
			}


		}
	}
}
